package com.moter.demo01.requirements.socket_threadpool;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

public class Server {
    private ServerSocket server = null;
    public final static int PORT = 9090;
    private ExecutorService pool= null;

    /**
     * 初始化服务端参数
     */
    public void initServer(){
        try {
            server = new ServerSocket();
            server.bind(new InetSocketAddress(PORT),5);
            System.out.println("服务启动========");
            pool=new ThreadPoolExecutor(5, 5,
                    0L, TimeUnit.MILLISECONDS,new SynchronousQueue<>());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 接受客户端连接
     */
    public void start(){
        try {
            while(true){
                Socket accept = server.accept();
                //分配一个线程去处理请求
                try {
                    pool.execute(new ClientThread(accept));
                }catch (Exception e){ //这里捕获异常，如果线程池满了，就说明客户端连接数超过5个，去执行返回错误信息的操作
                    override(accept);
                }
            }
        }catch (IOException e){
            System.out.println(e.getMessage());
        }finally {
            pool.shutdown();
        }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.initServer();
        server.start();
    }

    /**
     * 返回错误信息
     * @param client
     */
    public void override(Socket client){
        try {
            OutputStream outputStream = client.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
            bufferedWriter.write("服务器爆满，请稍后再尝试");
            bufferedWriter.flush();
            bufferedWriter.close();
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
